'use strict';

import { Service } from 'egg'

import { EnumType } from '../model/enum'
import { v4 } from 'uuid';

export default class UserService extends Service {

  public async create(data) {
    const { isProject, superId, type } = data
    const { Enum, Project } = this.ctx.model as any;
    // 层次
    let tier = 0
    if (!isProject) {
      const enumModel = await Enum.findWithId(superId)
      tier = enumModel.tier + 1
    }
    if (tier > 2) {
      throw 'enum最多只能保存三层'
    }
    const { ctx } = this
    // 获取用户数据
    const userData = await ctx.getUserData()
    type === EnumType.FILE ? null : data.uuid = v4()
    const enumModel = await new Enum({
      ...data,
      tier,
      createTime: new Date(),
      createUser: userData._id,
    }).save();
    if (isProject) {
      await Project.addEnum(superId, enumModel._id)
    } else {
      await Enum.addEnum(superId, enumModel._id)
    }
  }

  public async update(id, data, uuid, path) {
    const { Enum } = this.ctx.model as any;
    // 当时第三层或者，有子集的时候不能修改
    const enumModel = await Enum.findWithId(id)
    const upData = { ...data }
    if(enumModel.type === EnumType.FILE) {
      upData.path = path
      upData.uuid = uuid
    }
    await Enum.updateWithId(id, data)
  }

  public async delete(id, superId) {
    const { Enum, Data, Project } = this.ctx.model as any;
    // 当时第三层或者，有子集的时候不能修改
    const enumModel = await Enum.findWithId(id)
    if(enumModel.children.length > 0) {
      throw '只有将所有子集全部删除，才能刪除'
    }
    if (enumModel.tier) {
      await Enum.removeChildren(superId, id)
    } else {
      await Project.removeEnum(superId, id)
    }
    // 删除 enum 下面所有的数据
    await Data.removeAllEnumData(enumModel._id)
    await Enum.removeEnum(id)
  }

  /**
   * 获取详情
   */
  public async show(id: string) {
    const { Enum } = this.ctx.model as any;
    return await Enum.findDetailWithId(id)
  }

  /**
   * 更新数据说明
   */
  public async updateDataShow(id: string, dataShow: string) {
    const { Enum } = this.ctx.model as any;
    return await Enum.updateWithId(id, {
      dataShow
    })
  }
}